package com.lsh.streamgd.sparql.impl;

import com.hp.hpl.jena.rdf.model.Model;
import com.lsh.streamgd.sparql.OWLParserSparql;
import com.lsh.streamgd.sparql.SparqlExecution;
import com.lsh.streamgd.utils.StringUtil;

import java.util.List;
import java.util.Map;

/**
 * Created by yesonme on 16-7-10.
 */
public class OWLParserSparqlImpl implements OWLParserSparql {
    private Model m;
    private String nsPrefixString;

    public OWLParserSparqlImpl(Model m) {
        this.m = m;
        nsPrefixString = StringUtil.getNsPrefixString(m.getNsPrefixMap());
    }

    @Override
    public List<Map<String, String>> getAllTables() {
        String query = nsPrefixString +
                "SELECT DISTINCT ?tableUri ?tableName " +
                "WHERE {" +
                "   ?tableUri a rdfs:Class ; " +
                "      rdfs:label ?tableName . " +
                "} ORDER BY ASC(?tableName)";
        return SparqlExecution.jQuery(m, query, "tableName", "tableUri");
    }

    @Override
    public List<Map<String, String>> getColumns(String columnUri) {
        String query = nsPrefixString +
                "SELECT DISTINCT ?columnUri ?columnName ?type " +
                "WHERE {" +
                "   ?columnUri a rdf:Property ; " +
                "      a ?type ; " +
                "      rdfs:domain <" + columnUri + "> ; " +
                "      rdfs:label ?columnName . " +
                "   FILTER (?type != rdf:Property)" +
                "} ORDER BY ASC(?columnName)";

        return SparqlExecution.jQuery(m, query, "columnUri", "columnName", "type");
    }

    @Override
    public void insertComment(String s, String c) {
        String update = nsPrefixString +
                "INSERT DATA {<" + s + "> rdfs:comment \"" + c + "\"} ";

        SparqlExecution.update(m, update);
    }

    @Override
    public void insertFilter(String s, String p, String o) {
        String update = nsPrefixString +
                "DELETE {<" + s + "> " + p + " ?o .} " +
                "WHERE {<" + s +"> " + p + " ?o . FILTER REGEX(?o, '" + o.split(" ")[0] + ".', 'i')}";
        SparqlExecution.update(m, update);

        update = nsPrefixString +
                "INSERT DATA {<" + s + "> " + p + " \"" + o + "\" .}";
        SparqlExecution.update(m, update);
    }

    @Override
    public List<Map<String, String>> getTraceColumns() {
        String query = nsPrefixString +
                "SELECT DISTINCT ?class ?property " +
                "WHERE {" +
                "   ?property a rdf:Property ; " +
                "      rdfs:domain ?class . " +
                "}";

        return SparqlExecution.jQuery(m, query, "class", "property");
    }
}
